/**
 * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */
package com.liferay.analystest.controller;

import com.liferay.analystest.util.Const;
import com.liferay.analystest.window.MainWindow;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Dante Wang
 */
public class MainWindowController implements ActionListener {

	public MainWindowController() throws Exception {
		MAINWINDOW = new MainWindow();

		init();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String command = e.getActionCommand();

		int i = -1;

		if (command.startsWith(Const.COMMAND_CHART_TOOLBAR_BTN)) {
			command =
				command.substring(Const.COMMAND_CHART_TOOLBAR_BTN.length());

			switch (command) {
				case "Refresh":
					i = MAINWINDOW.getSelectedChartTab();

					try {
						_chartControllers.get(i).update();
					}
					catch (Exception ex) {

					}

					break;
				case "SaveChart":
					i = MAINWINDOW.getSelectedChartTab();

					try {
						_chartControllers.get(i).CHART.doSaveAs();
					}
					catch (Exception ex) {

					}

					break;
			}
		}
	}

	private void init() throws Exception {
		_chartControllers = new ArrayList<>();

		for (String caseDir : Const.CASE_DIRS) {
			Path p = Paths.get(Const.BASE_DIR.concat(caseDir));

			ChartPaneController cpc = new ChartPaneController(p);

			cpc.update();

			_chartControllers.add(cpc);

			MAINWINDOW.addChartTab(caseDir, cpc.CHART);
		}

		MAINWINDOW.setToolBarActionListener(this);

		MAINWINDOW.validate();
	}

	public final MainWindow MAINWINDOW;
	private List<ChartPaneController> _chartControllers;

}